
package com.michaelwolf.mytool.wcfcompmanger.wcfanalyzer;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.w3c.dom.Node;

import com.michaelwolf.mytool.wcfcompmanger.wcfanalyzer.WCFLoader.TraverseCacheData;

public class WCFManager {
	private WCFLoader loader;
	
	private boolean loadDone = false;
	
	private WCFManager() {
		super();
		this.loader = new WCFLoader();
		startLoadingThread();
	}
	
	public boolean isLoadDone() {
		return loadDone;
	}

	private void startLoadingThread() {
		new Thread(){
			@Override
			public void run() {
				loadAll();
				
				loadDone = true;
				super.run();
			}

			private void loadAll() {
				List<String> allModuleNames = getAllModuleName();
				loader.loadWCFModule(allModuleNames);
				loader.findRelateship(allModuleNames);
				
			}
			
		}.start();
		
	}

	public static WCFManager createNewWCFManager(){
		return new WCFManager();
	}
	
	public List<Node> findAllUnusedComponent(List<String> targetModuleNameList){
		loader.loadWCFModule(targetModuleNameList);
		Map<String, Node> targetModuleIdMap = new HashMap<String, Node>();
		targetModuleIdMap.putAll(loader.getTraverseCacheData().getComponentIdMap());
		
		List<String> allModuleNames = getAllModuleName();
		
		
		
		loader.loadWCFModule(removeTargetModuleName(allModuleNames, targetModuleNameList));
		loader.findRelateship(allModuleNames);
		
		Map<Node, Set<Node>> dependencyNodeMap = loader.getTraverseCacheData().getDependencyMap();
		Collection<Node> targetModuleNodes = targetModuleIdMap.values();
		
		List<Node> result = new ArrayList<Node>();
		for(Node node : targetModuleNodes){
			if(dependencyNodeMap.get(node)==null || dependencyNodeMap.get(node).size()==0){
				result.add(node);
			}
		}
		
		
		return result;
	}
	
	private List<String> removeTargetModuleName(List<String> allModuleNames, List<String> targetModuleNameList) {
		List<String> result = new ArrayList<String>();
		
		for(String moduleName : allModuleNames){
			
			boolean found = false;
			for(String targetModuleName : targetModuleNameList){
				if(targetModuleName.equals(moduleName)){
					found = true;
				}
			}
			if(!found){
				result.add(moduleName);
			}
		}
		
		return result;
	}
	
	public void searchNode(String keyword, List<String> moduleNames) throws Exception{
		loader.searchNode(keyword, moduleNames);
	}
	
	public TraverseCacheData getTraverseCacheData(){
		return loader.getTraverseCacheData();
	}


	public List<String> getAllModuleName() {
		File wcfDirFile = new File(WCFLoader.WCFDIR);
		File[] fileList = wcfDirFile.listFiles();
		
		List<String> moduleNameList = new ArrayList<String>();
		for(File modulefiledir : fileList){
			if(modulefiledir.isDirectory()){
				moduleNameList.add(modulefiledir.getName());
			}
		}
		
		return moduleNameList;
	}
}
